#!/usr/bin/perl -w
use Bio::SeqIO;
use Getopt::Long;
# use the cmdline!
my @dirs = @ARGV;

# we ran this script like this:
# perl scripts/subFamily_split_merge.pl cglo ncra ndis tter smac sthe ntet
# in the directory 
# /home_stajichlab/yzhou/projects/fungal_TE/TE_fam

my $outputdir = 'TE_fams';
my $format    = 'fasta';
# also read up
# by doing perldoc Getopt::Long

GetOptions(
	   'o|out:s' => \$outputdir,
	   
	   );

# make the output directory (unless it already exists)
mkdir($outputdir) unless -d $outputdir;

# use this hash to store all the families
my %family;
foreach my $dir ( @dirs ) {
    opendir(DIR, $dir) || die "cannot open directory $dir: $!";
    foreach my $file ( readdir(DIR) ) {
	next unless( $file =~ /\.fas$/);
#	print "file is $file\n";
	my $class = $file;
	$class =~ s/\.fas$//;
	my ($first,$second) = split(/_/,$class,2);
	$class = $second;
#	print "class is $class\n"; # debugging statement
# a regular expression would also work
#	if( $file =~ /\w+_(\S+)\.fas$/  ){
#          $class = $1;
#	}
	my $seqin = Bio::SeqIO->new(-format => $format,
				    -file   => "$dir/$file");
	while( my $seq = $seqin->next_seq ) {
	    my $id = $seq->display_id; # or you can say $seq->id your choice	    
	    my $family_name = $seq->description; # sequence description -- everything AFTER the 1st white space
	    push @{$family{$class}->{$family_name}}, $seq; 
# this is KIND-OF like doing this (except this won't quite work due to references), you have to copy back
#	    $family{$class} ||= {};
#	    my %families = %{$family{$class}};
#	    $families{$family_name} ||= [];
#	    my @listofseqs = @{$families{$family_name}};
#	    push @listofseqs, $seq;
#           @{$families{$family_name}} = @listofseqs
#           %{$family{$class}} = %families;
	    
	}
    }
}

while( my ($class,$families) = each %family ) {
#    print "class is $class\n";
    mkdir("$outputdir/$class");
    while( my ($family_name,$seqs) = each %$families) {
#	print "family name is $family_name\n";
	my $seqout = Bio::SeqIO->new(-file => ">$outputdir/$class/$family_name.fas",
				     -format => $format);
	foreach my $seq ( @$seqs ) {
	    $seqout->write_seq($seq);
	}
    }
}
